﻿using System;
using System.Data;
using System.Data.SqlClient;
using VIT.DataHelper.DataAccess;

public partial class update : System.Web.UI.Page
{
    SQLSupport sqlSupport = new SQLSupport();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            int vId;
            int.TryParse(Request.QueryString["id"], out vId);
            int vplus; //1: thêm | 0 bớt
            int.TryParse(Request.QueryString["plus"], out vplus);

            divXuat.InnerText = UpdateGioHang(vId, vplus).ToString();
        }
        catch
        {
        }
    }

    protected int UpdateGioHang(int id, int plus)
    {
        DataTable dt = (DataTable)Session["GioHang"];

        bool co = false;
        foreach (DataRow dr in dt.Rows)
        {
            if (Convert.ToInt32(dr["ProductID"]) == id)
            {
                int SoLuong;
                if (int.TryParse(dr["Quantity"].ToString(), out SoLuong))
                {
                    if (plus == 1) dr["Quantity"] = SoLuong + 1;
                    else // plus==0 bot san pham
                    {
                        if (SoLuong > 0) SoLuong--;
                        dr["Quantity"] = SoLuong;
                    }
                }
                decimal DonGia;
                if (decimal.TryParse(dr["UnitPrice"].ToString(), out DonGia))
                {
                    dr["TotalCost"] = SoLuong * DonGia;
                }
                co = true;
                break;
            }
        }

        if (co == false)
        {
            DataTable table = new DataTable();
            if (Exist(id))
            {
                string strQuery = "select CategoryId, Title, ManufacturerId, SupplierId, Image, Brief, Description, Price, Sale, Views, Tag, Type, Orders, Published from Products join Products_Language on Id=ProductId and LanguageId=@LanguageId where Id=@Id and Published=1 ";
                SqlParameter Id = new SqlParameter("@Id", id);
                SqlParameter LanguageId = new SqlParameter("@LanguageId", Session["Language"]);
                table = sqlSupport.ExecuteDataset(false, strQuery, Id, LanguageId).Tables[0];
            }
            if (table.Rows.Count > 0)
            {
                dt.Rows.Add(id, table.Rows[0]["Title"].ToString(), table.Rows[0]["Image"].ToString(), 1, table.Rows[0]["Sale"].ToString(), table.Rows[0]["Sale"].ToString(), Session["Language"].ToString());
            }
        }

        int soLuong, total = 0;
        foreach (DataRow dr in dt.Rows)
            if (int.TryParse(dr["Quantity"].ToString(), out soLuong)) total += soLuong;
        return total;
    }

    private bool Exist(int id)
    {
        string strQuery = "select Id from Products where Id=@Id";
        SqlParameter Id = new SqlParameter("@Id", id);
        return sqlSupport.ExecuteScalar(false, strQuery, Id) != null;
    }
}